package com.ruoyi.web.controller.netty.http.custom;

import com.ruoyi.common.utils.uuid.UUID;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.Date;

@Slf4j
public class HttpNettyHandler extends ChannelInboundHandlerAdapter {

    /**
     * 读取到的数据
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //netty中封装的http请求
        FullHttpRequest httpRequest = (FullHttpRequest)msg;
        String uri = httpRequest.uri();
        log.info("请求的路径为：" + uri);
        String body = httpRequest.content().toString(CharsetUtil.UTF_8);
        log.info("获取到的请求体的数据为：" + body);
        if ("/test".equals(uri)){
            send(ctx,HttpResponseStatus.OK,"请求成功!");
        }else{
            send(ctx,HttpResponseStatus.NOT_FOUND,"路径不存在!");
        }
    }

    public void send(  ChannelHandlerContext ctx,HttpResponseStatus responseStatus, String context){
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        FullHttpResponse response = new DefaultFullHttpResponse(
                HttpVersion.HTTP_1_1,
                responseStatus,
                Unpooled.copiedBuffer(date + "--------" + context,CharsetUtil.UTF_8)
        );
        response.headers().set(HttpHeaderNames.CONTENT_TYPE,"text/plain;charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

    //进入时想要触发的事件
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("客户端的地址为：" + ctx.channel().remoteAddress());
    }
}
